package lab.poc.erl.showcase.timer;

import java.util.ArrayList;
import java.util.List;

import lab.poc.erl.Node;

/**
 * Demonstrates receive with a timeout. Inspired by sections 8.5 - 8.7 of Joe
 * Armstrong's Programming Erlang book.
 */
public final class TimerShowcase {

	// tick every CLOCK_PERIOD / 1000 secs
	private static final long CLOCK_PERIOD = 2000L;
	// for a total of MAX_CLOCK_TICKS
	private static final int MAX_CLOCK_TICKS = 6;

	public static void main(String[] args) {
		System.out.println(TimerShowcase.class.getSimpleName() + " started");

		// arguments for the clock actor
		List<Object> clockActorArgs = new ArrayList<Object>();
		clockActorArgs.add(CLOCK_PERIOD);
		clockActorArgs.add(MAX_CLOCK_TICKS);

		Node env = Node.getNode();
		// create a dummy actor for the main thread, so that
		// it can start actors and communicate with them
		env.createMockProcessForCurrentThread();
		// start the clock actor and link it to the main thread's
		// dummy actor
		env.spawnLink(Clock.class, clockActorArgs);

		// wait for the clock actor to finish
		waitForTermination(TimerShowcase.class);
	}

	private static void waitForTermination(final Class<?> showcaseClass) {
		// exploit the fact that we have linked the clock actor to our main
		// thread's dummy actor. So we'll be notified via interrupt() when the
		// clock actor exits.
		final Object dummyMonitor = new Object();
		synchronized (dummyMonitor) {
			try {
				dummyMonitor.wait();
			} catch (InterruptedException e) {
				System.out.println(showcaseClass.getSimpleName()
						+ " main program done");
			}
		}
	}
}
